package org.douxiaoban.client.activity;

import java.util.ArrayList;

import org.douxiaoban.client.R;
import org.douxiaoban.client.adapter.TopAdapter;
import org.douxiaoban.client.api.TopSubjectRecord;
import org.douxiaoban.client.app.App;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.model.BundleSerializable;
import org.douxiaoban.client.util.ThreadTool;
import org.douxiaoban.client.widget.GalleryFlow;
import org.douxiaoban.client.widget.PopupRecommend;
import org.douxiaoban.client.widget.TitleStyle;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.mobclick.android.MobclickAgent;


/**
 * Created by IntelliJ IDEA.
 * User: huangzhongkun
 * Date: 11-6-15
 * Time: 下午4:37
 */
public class TopActivity extends BaseActivity {
    private ThreadTool _thread;
    private TopAdapter _top_adapter ;
    private GalleryFlow _galleryFlow;
    private ArrayList<TopSubjectRecord> topSubjectRecords;
    private TextView _top_name_tx;
    private TextView _top_rating_evage_tx;
    private TextView _top_assess_tx;
    private TextView _top_attribute_tx;
    private RatingBar _top_rating_evage_bar;
    private ImageView _top_category_img;
    private TitleStyle titleStyle;
     private String _type;
    private PopupRecommend _popup_recommend;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.tophot);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);

        titleStyle = new TitleStyle(this);
        titleStyle.initTitleStyle();
        _thread = ThreadTool.instace(this);

        _type = getIntent().getStringExtra(Assistant.KEY_OF_TYPE);

        if(_type ==null)
        _type = Assistant.STATUS_MUSIC;

        topSubjectRecords = new ArrayList<TopSubjectRecord>();
        ImageView defaultImageView =  createReflectedImages(
                BitmapFactory.decodeResource(getResources(),R.drawable.default_bg_image));
        _top_adapter = new TopAdapter(defaultImageView);

        _thread.startThreadFetchTopSubject(_handler, _type);


        _popup_recommend = new PopupRecommend(this);
         setupView();
         setupListener();
    }

    private void setupView(){
        _galleryFlow = (GalleryFlow)findViewById(R.id.top_gallery_flow);
        _galleryFlow.setSpacing(-50);
                _galleryFlow.setAdapter(_top_adapter);


                _top_name_tx = (TextView)findViewById(R.id.top_name);
                _top_rating_evage_bar = (RatingBar)findViewById(R.id.top_rating_bar);
                _top_rating_evage_tx = (TextView)findViewById(R.id.top_rating_evage);
                _top_assess_tx = (TextView)findViewById(R.id.top_assess);
                _top_attribute_tx = (TextView)findViewById(R.id.top_attribute_tx);
                _top_category_img = (ImageView)findViewById(R.id.top_category_img);


        if(_type.equals(Assistant.STATUS_BOOK)){
                    _top_rating_evage_bar.setVisibility(View.GONE);
                    _top_rating_evage_tx.setVisibility(View.GONE);
                    _top_assess_tx.setVisibility(View.GONE);
                    _top_category_img.setImageDrawable(getResources().getDrawable(R.drawable.search_book_img));
        }

        if(_type.equals(Assistant.STATUS_MUSIC))
            _top_category_img.setImageDrawable(getResources().getDrawable(R.drawable.search_music_img));
    }

    private void setupListener(){
         _galleryFlow.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                TopSubjectRecord topSubjectRecord = topSubjectRecords.get(i);
                if(topSubjectRecord==null)return;

                if(topSubjectRecord.title!=null)
                _top_name_tx.setText(topSubjectRecord.title);

                if(topSubjectRecord.rating_num!=null){
                 _top_rating_evage_bar.setRating(Float.valueOf(topSubjectRecord.rating_num)/2);
                 _top_rating_evage_tx.setText(String.valueOf(topSubjectRecord.rating_num));
                }else {
                 _top_rating_evage_bar.setRating(0);
                 _top_rating_evage_tx.setText("0.0");
                }
                if(topSubjectRecord.rating_average!=null)
                 _top_assess_tx.setText(topSubjectRecord.rating_average);

                if(topSubjectRecord.content!=null){

                    if(topSubjectRecord.content.length()>60 && !_type.equals(Assistant.STATUS_BOOK))
                       topSubjectRecord.content = topSubjectRecord.content.substring(0,60)+"...";

                    if(_type.equals(Assistant.STATUS_BOOK) && topSubjectRecord.content.length()>100)
                       topSubjectRecord.content = topSubjectRecord.content.substring(0,100)+"...";

                    if(_type.equals(Assistant.STATUS_MOVICE) && topSubjectRecord.content.length()>25 ){
                        topSubjectRecord.content = topSubjectRecord.content.substring(0,25)+"...";
                     }

                _top_attribute_tx.setText(topSubjectRecord.content);
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
             //do something
            }
        }); ;

        _galleryFlow.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TopSubjectRecord topSubjectRecord = topSubjectRecords.get(i);
                if(topSubjectRecord == null)
                return;

                Intent intent = new Intent(TopActivity.this,CollectionSubjectActivity.class);
                intent.putExtra(Assistant.KEY_OF_INTENT_CATEGORY,_type);
                String[] s= topSubjectRecord.id.split("/");

                intent.putExtra(Assistant.KEY_OF_INTENT_ID,s[s.length-1]);
                startActivity(intent);
            }
        });
    }

    private Handler _handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Assistant.FETCH_PARSER_TOP_DONE:
                    Bundle bundle = msg.getData();
                    BundleSerializable bs =
                            (BundleSerializable)bundle.getSerializable(Assistant.KEY_OF_SUBJECT);

                    String[] imgs = new String[bs.tsr.size()];
                    int i = 0;
                    if(bs.tsr.size()>0){
                        for(TopSubjectRecord tr :bs.tsr){
                            if(tr.image_url!=null)
                            imgs[i] = tr.image_url;
                            ImageView imageview = createReflectedImages(
                                    BitmapFactory.decodeResource(getResources(),R.drawable.default_bg_image));
                            tr.default_image = imageview;

                            //open thread
                            _thread.startThreadImageDownload(Assistant.STATUS_MOVICE,tr.image_url,_handler,i);
                            i++;
                        }
                    }
                    topSubjectRecords = bs.tsr;
                    _top_adapter.topSubjectRecordArrayList = topSubjectRecords;
                    _top_adapter.notifyDataSetChanged();
                    findViewById(R.id.top_progress_lay).setVisibility(View.GONE);
                    findViewById(R.id.top_content_lay).setVisibility(View.VISIBLE);
                    //_thread.startThreadFetchReviewAvatar(_handler,imgs,TopActivity.this);
                    break;
                case Assistant.FETCH_PARSER_TOP_FAIL:
                    _popup_recommend.showToastWindow(0,getString(R.string.load_fail));
                    finish();
                    break;

                case Assistant.FETCH_REVIEW_AVATAR_DONE:
                    BundleSerializable bundleSerializable =
                            (BundleSerializable)msg.getData().getSerializable(Assistant.KEY_OF_IMAGE);

                    int j=0;
                    for(TopSubjectRecord record:topSubjectRecords){

                        record.image_bitmap = createReflectedImages(bundleSerializable.reviewAvatars.get(j));
                        j++;
                    }
                    _top_adapter.notifyDataSetChanged();
                    break;
                case Assistant.FETCH_BOOK_WISH_IMAGE_DONE:
                    Bundle imgbundle = msg.getData();
                    ThreadTool.ImageSerialz is =
                            (ThreadTool.ImageSerialz)imgbundle.getSerializable(Assistant.THREAD_IMAGE_KEY);
                    topSubjectRecords.get(is.m_iPosition).image_bitmap = createReflectedImages(is.m_bitmap);
                    _top_adapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    };

    public ImageView createReflectedImages(Bitmap originalImage) {
        if(originalImage==null)return null;

        originalImage = zoomBitmap(originalImage);
       final int reflectionGap = 4;
                int index = 0;

                        int width = originalImage.getWidth();
                        int height = originalImage.getHeight();

                        Matrix matrix = new Matrix();
                        matrix.preScale(1, -1);

                        Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
                                        height / 2, width, height / 2, matrix, false);

                        Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
                                        (height + height / 2), Bitmap.Config.ARGB_4444);

                        Canvas canvas = new Canvas(bitmapWithReflection);

                        canvas.drawBitmap(originalImage, 0, 0, null);

                        Paint deafaultPaint = new Paint();
                        canvas.drawRect(0, height, width, height + reflectionGap,
                                        deafaultPaint);

                        canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

                        Paint paint = new Paint();
                        LinearGradient shader = new LinearGradient(0, originalImage
                                        .getHeight(), 0, bitmapWithReflection.getHeight()
                                        + reflectionGap, 0x70ffffff, 0x00ffffff, Shader.TileMode.CLAMP);

                        paint.setShader(shader);

                        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

                        canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
                                        + reflectionGap, paint);

                        ImageView imageView = new ImageView(this);
                        imageView.setImageBitmap(bitmapWithReflection);
                        GalleryFlow.LayoutParams params =
                                new GalleryFlow.LayoutParams(App.dip2px(this,180),
                                        App.dip2px(this,260));

                        imageView.setLayoutParams(params);


                        imageView.setScaleType(ImageView.ScaleType.MATRIX);

          reflectionImage.recycle();
          //bitmapWithReflection.recycle();

                return imageView;
    }

    public Bitmap zoomBitmap(Bitmap bitmap){
           int width = bitmap.getWidth();
           int height = bitmap.getHeight();

        int nWidth = App.dip2px(this,150);
        int nHeight = App.dip2px(this,200);

        float scaleWidth = ((float )nWidth)/width;
        float scaleHeight = ((float)nHeight)/height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth,scaleHeight);

        Bitmap resizeBitmap = Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true);
        return resizeBitmap;
    }

 
}